<?php

namespace App\Http\Middleware;

use Closure;

class CheckAdminLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
//        dump($param);
//        echo "<h3>我是一个中间件</h3>";

        //用户是否登陆检查
        if (!auth()->check()) {
            return redirect(route('admin.login'))->withErrors(['error' => '请登陆']);
        }

        //访问本路由的权限

        $can_routes = [];
        if (auth()->user()->username != config('rbac.super')) {

            $can_routes = array_filter(session('admin.node_ids'));  //清掉""的项目
            $can_routes = array_merge($can_routes, config('rbac.allow_route')); //合并不验证的route
            $current_route = $request->route()->getName(); //"admin.index"

            if (!in_array($current_route, $can_routes)) {
                exit("你没有权限");
            }
        }

        //使用request传到下级去
        $request->can_routes = $can_routes;


        /*
         * array:4 [▼
          1 => ""
          2 => "admin.user.index"
          3 => "admin.role.index"
          5 => ""
        ]*/


        //如果没有停止则向后执行
        return $next($request);
    }
}
